﻿#include "chatclient.h"

#include <QDebug>
#include <QHostAddress>
#include <QThread>

class ChatClientPrivate {
public:
  QThread *clientThread;
};

ChatClient::ChatClient(QObject *parent)
    : QTcpSocket(parent), clientPrivate(new ChatClientPrivate) {
  clientPrivate->clientThread = new QThread();

  connect(this, &ChatClient::readyRead, this, &ChatClient::readMsg,
          Qt::DirectConnection);
}

ChatClient::~ChatClient() { qDebug() << "client delete"; }

bool ChatClient::setSocketDescriptor(qintptr socketDescriptor,
                                     QAbstractSocket::SocketState state,
                                     QIODevice::OpenMode openMode) {
  return QTcpSocket::setSocketDescriptor(socketDescriptor, state, openMode);
}

void ChatClient::start() {
  this->moveToThread(clientPrivate->clientThread);
  clientPrivate->clientThread->start();
}

void ChatClient::stop() {
  this->close();

  clientPrivate->clientThread->quit();

  qDebug() << "chatserver actively disconnects";
}

void ChatClient::readMsg() {
  QByteArray rawMsg = this->readAll();

  emit receiveMsg(rawMsg);
}

void ChatClient::writeMsg(const QByteArray &msg) { this->write(msg); }
